package com.springboot.springbootlogindemo.service.serviceImpl;

import com.springboot.springbootlogindemo.domain.User;
import com.springboot.springbootlogindemo.repository.UserDao;
import com.springboot.springbootlogindemo.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public User loginService(String name, String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder =new BCryptPasswordEncoder();
        // 如果账号密码都对则返回登录的用户对象，若有一个错误则返回null
        User user = userDao.findByName(name);
        if(user==null){
            return null;
        }
        String encodedPassword = user.getPassword();

        // 重要信息置
        if(bCryptPasswordEncoder.matches(password, encodedPassword)){
            user.setPassword("");
            return user;
        }
        return null;
    }

    @Override
    public User registService(User user) {
        //当新用户的用户名已存在时
        if(userDao.findByName(user.getName())!=null){
            // 无法注册
            return null;
        }else{
            BCryptPasswordEncoder bCryptPasswordEncoder =new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode(user.getPassword());
            user.setPassword(encode);
            //返回创建好的用户对象(带id)
            User newUser = userDao.save(user);
//            if(newUser != null){
//                newUser.setPassword("");
//            }
            return newUser;
        }
    }
}
